package com.intel.factorytest.activity;


import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.intel.factorytest.R;

public class Video extends BaseActivity implements OnClickListener,
        SurfaceHolder.Callback,OnCompletionListener{
    private final String TAG  = "Video";
    Button playButton;
    Button pauseButton;
    Button successButton;
    Button failButton;
    Button replayButton;
    boolean isPlaying = true;
    SurfaceHolder surfaceHolder;
    private MediaPlayer mediaPlayer;
    SurfaceView surfaceView;
    private TextView durationTime = null;
    private TextView currentTime = null;
    private static final int UPDATE = 1;
//    private Timer mTimer;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video);
        Intent intent = getIntent();
//        test_pos = intent.getIntExtra(TEST_ITEM, -1);
        initView();
    }
    
    protected void initView() {
        currentTime = (TextView) findViewById(R.id.currentTime);
        durationTime = (TextView) findViewById(R.id.totalTime);
        playButton = (Button) findViewById(R.id.playButton);
        playButton.setOnClickListener(this);
        pauseButton = (Button) findViewById(R.id.pauseButton);
        pauseButton.setOnClickListener(this);
        getWindow().setFormat(PixelFormat.UNKNOWN);
        mediaPlayer = new MediaPlayer();
        surfaceView = (SurfaceView) findViewById(R.id.videoView);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // MediaPlayer.create(this, R.raw.video);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        playButton.setText(getString(R.string.SERVICEMENU_VIDEO_PAUSE_TXT));
        mediaPlayer.setOnCompletionListener(this);
        
        successButton = (Button) findViewById(R.id.successButton);
        successButton.setOnClickListener(this);
        failButton = (Button) findViewById(R.id.failButton);
        failButton.setOnClickListener(this);
        replayButton = (Button) findViewById(R.id.repeatButton);
        replayButton.setOnClickListener(this);
    }

    private Uri getMediaVolumeUri(Context context) {
        System.out.println("tangjun video: uri=" + Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + context.getPackageName() + "/" + R.raw.video).toString());
        return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + context.getPackageName() + "/" + R.raw.video);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i(TAG, "handleMessage");
            if (msg.what == UPDATE) {
                if (mediaPlayer == null)
                    return;
                int position = mediaPlayer.getCurrentPosition() / 1000;
                int total = mediaPlayer.getDuration() / 1000;
                currentTime.setText("00:0" + position);
                durationTime.setText("00:0" + total);
            }

        }
    };

    @Override
    protected void onResume() {
        Log.i(TAG, "onResume");
        super.onResume();
//        mTimer = new Timer();
//        mTimer.schedule(new TimerTask() {
//
//            @Override
//            public void run() {
//                mHandler.sendEmptyMessage(UPDATE);
//            }
//
//        }, 500, 500);
    }

    @Override
    protected void onPause() {

        super.onPause();

    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy()");
        if (mediaPlayer != null)
            mediaPlayer.release();
        mediaPlayer= null;
        super.onDestroy();

    }

    public void onClick(View v) {
        if (v == playButton) {
            if (isPlaying == true) {
                Log.i("meilianggang", "mediaPlayer.pause()");
                if (mediaPlayer != null) {
                    if (!mediaPlayer.isPlaying() == true) {
                        return;
                    }
                } else {
                    return;
                }
                mediaPlayer.pause();
                playButton
                        .setText(getString(R.string.SERVICEMENU_VIDEO_PLAY_TXT));
                isPlaying = false;
            } else {
                Log.i("meilianggang", "mediaPlayer.start()");
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying() == true) {
                        return;
                    }
                } else {
                    return;
                }
                mediaPlayer.start();
                playButton
                        .setText(getString(R.string.SERVICEMENU_VIDEO_PAUSE_TXT));
                isPlaying = true;
            }
        } else if (v == pauseButton) {
            finish();
        } else if (v == successButton) {
            v.setClickable(false);
            is_pass = true;
            finish();
        } else if (v == failButton) {
            v.setClickable(false);
            is_pass = false;
            finish();
        } else if (v == replayButton) {
            stop_mp();
            start_mp();
        }
    }
    
    private void stop_mp() {
        Log.i(TAG, "stop_mp()");
        if (mediaPlayer!=null)
        {
            if (mediaPlayer.isPlaying())
                mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
    
    private void start_mp() {
        try {
            Log.i(TAG, "start_mp()");
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDisplay(surfaceHolder);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(this, getMediaVolumeUri(this));
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        Log.i(TAG, "surfaceChanged");

    }

    public void surfaceCreated(SurfaceHolder holder) {
        Log.i(TAG, "surfaceCreated");
        surfaceHolder = holder;
        if (mediaPlayer != null) {
            try {
                mediaPlayer.setDisplay(surfaceHolder);
                mediaPlayer.setDataSource(this, getMediaVolumeUri(this));
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.i(TAG, "surfaceDestroyed");
        holder.removeCallback(this);  
    }

    @Override
    public void finish() {
//        tc.setTestResult(is_pass);
//        mHandler.removeMessages(UPDATE);
//        mTimer.cancel();
        Log.i(TAG, "finish()");
        super.finish();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        Log.i(TAG, "onCompletion()");
        stop_mp();
    }
}
